#include <stdio.h>
#include <stdlib.h>
#include "single_list.h"

#if defined(_SINGLE_LIST_VER2)

struct s_node
{
    struct s_node *next;
    char name[12];
    int elem;
};

_SNode *create_node(void)
{
    _SNode *new_node = NULL;

    new_node = (_SNode *)malloc(sizeof(_SNode));
    if (NULL == new_node)
    {
	return NULL;
    }

    new_node->next = NULL;
    memset(new_node->name, 0, NAME_LEN);
    new_node->elem = 0;

    return new_node;
}

int destroy_node(_SNode *node)
{
    if (NULL == node)
    {
	return -1;
    }

    free(node);
    return 0;
}

int init_node(_SNode *node, int val)
{
    if (NULL == node)
    {
	return -1;
    }

    node->elem = val;
    return 0;
}

_SList create_list(void)
{
    _SList new_list = NULL;
    
    new_list = (_SList)malloc(sizeof(*new_list));
    if (NULL == new_list)
    {
	return NULL;
    }

    new_list->next = NULL;
    memset(new_list->name, 0, NAME_LEN);
    new_list->elem = 0;

    return new_list;
}

void destroy_list(_SList head)
{
    _SNode *tmp = NULL;

    if (NULL == head)
    {
	return;
    }

    for(tmp = head->next; NULL != tmp; tmp = head->next)
    {
	if (NULL != tmp->next)
	{
	    head->next = tmp->next;
	}

	free(tmp);
    }

    free(head);
    return;
}

int insert_to_list(_SList list, _SNode *node)
{
    if (NULL == list || NULL == node)
    {
	return -1;
    }

    node->next = list->next;
    list->next = node;
    return 0;
}

int delete_node(_SList head, void *key)
{
    _SNode *prev = NULL;
    _SNode *del = NULL;
    int k = (int)key;

    if (NULL == head)
    {
	return -1;
    }

    prev = head;
    for(prev; NULL != prev->next;)
    {
	if (prev->next->elem == k)
	{
	    del = prev->next;
	    prev->next = prev->next->next;
	    free(del);
	    del = NULL;
	    continue;
	}

	prev = prev->next;
    }

    return 0;
}

void print_list(_SList head)
{
    _SNode *tmp = NULL;
    for (tmp = head->next; tmp != NULL; tmp = tmp->next)
     {
         printf("%d\n", tmp->elem);
     }
}

int for_each_node(_SList list, void *(* func)(void *))
{

}

#endif
